package com.example.demo.service;

import com.example.demo.entity.Semester;
import com.example.demo.mapper.SemesterMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class SemesterService {

    @Autowired
    private SemesterMapper semesterMapper;

    // 创建新学期
    public Semester createSemester(Semester semester) {
        // 业务校验：确保学期名称和时间不为空（修正属性名）
        if (semester.getName() == null || semester.getStartDate() == null || semester.getEndDate() == null) {
            throw new IllegalArgumentException("学期名称和时间范围不能为空");
        }
        if (semesterMapper.insert(semester) > 0) {
            return semester;
        } else {
            throw new RuntimeException("学期创建失败");
        }
    }

    // 获取所有学期
    public List<Semester> findAllSemesters() {
        return semesterMapper.findAll();
    }

    // 根据ID获取学期（确认参数类型与Mapper一致）
    public Optional<Semester> findSemesterById(Integer semesterId) {
        return semesterMapper.findById(semesterId);
    }

    // 更新学期信息（修正属性名）
    public boolean updateSemester(Semester semester) {
        if (semester.getId() == null || !semesterMapper.findById(semester.getId()).isPresent()) {
            return false;
        }
        return semesterMapper.update(semester) > 0;
    }

    // 删除学期
    public boolean deleteSemester(Integer semesterId) {
        return semesterMapper.deleteById(semesterId) > 0;
    }
}